<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">企业名称：</span>
      <el-input v-model="searchForm.enterpriseName" clearable placeholder="请输入企业宇名称" class="search-main" />

      <span class="search-label">缴费时间：</span>
      <el-date-picker
        v-model="searchForm.paymentPeriod"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      />

      <el-button type="primary" class="search-btn" @click="chaxun">查询</el-button>

    </div>

    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button
        type="primary"
        @click="flagOk"
      >添加账单</el-button>

    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="parklist">
        <el-table-column type="index" label="序号" />
        <!-- prop="给表格关联字段" -->
        <el-table-column label="账单编号" prop="billNumber" />
        <el-table-column label="企业名称" prop="enterpriseName" />
        <el-table-column label="租赁楼宇" prop="buildingName" />
        <el-table-column label="物业费(元/m²)" prop="propertyFeePrice" />
        <el-table-column label="账单金额（元）" prop="paymentAmount" />
        <el-table-column label="缴费时间" fixed="right" width="180" prop="createTime" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="chakan(row.id)">查看</el-button>
            <el-button size="mini" type="text" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <div class="page-container">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加账单 -->
    <!-- :visible.sync="flag"显示状态 -->
    <el-dialog
      title="添加账单"
      width="580px"
      :visible.sync="flag"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="formModel" :model="formModel">
          <el-form-item label="选择租户" prop="selectedPark">
            <el-select v-model="formModel.selectedPark" placeholder="请选择租户">
              <el-option
                v-for="item in getPark"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁楼宇" prop="selectedBuilding">
            <el-select v-model="formModel.selectedBuilding" placeholder="请选择楼宇">
              <el-option
                v-for="item in getBuilding"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="缴费周期" prop="paymentPeriod">
            <el-date-picker
              v-model="formModel.paymentPeriod"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>

          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input v-model="formModel.paymentAmount" />
          </el-form-item>

          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="formModel.paymentMethod" placeholder="请选择支付方式">
              <el-option
                v-for="item in paymentMethodValue"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="flag=false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addFn">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 查看账单 -->
    <el-dialog
      title="查看账单"
      width="580px"
      :visible.sync="FLAG"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="viewForm" :model="viewForm" label-width="100px">
          <el-form-item label="账单编号">
            <el-input v-model="viewForm.billNumber" disabled />
          </el-form-item>

          <el-form-item label="楼宇名称">
            <el-input v-model="viewForm.buildingName" disabled />
          </el-form-item>

          <el-form-item label="开始时间">
            <el-input v-model="viewForm.startTime" disabled />
          </el-form-item>

          <el-form-item label="结束时间">
            <el-input v-model="viewForm.endTime" disabled />
          </el-form-item>

          <el-form-item label="企业名称">
            <el-input v-model="viewForm.enterpriseName" disabled />
          </el-form-item>

          <el-form-item label="支付金额">
            <el-input v-model="viewForm.paymentAmount" disabled />
          </el-form-item>

          <el-form-item label="支付方式">
            <el-input v-model="viewForm.paymentMethodValue" disabled />
          </el-form-item>

          <el-form-item label="物业费单价">
            <el-input v-model="viewForm.propertyFeePrice" disabled />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="FLAG=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script>
import { getPropetyList, getParkList, getBuildingList, addpropertyAPI, deletePropertyAPI, lookAPI } from '@/api/propety'
export default {
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      parklist: [], // 物业费列表
      enterpriseName: '',
      start: '',
      end: '',
      flag: false,
      FLAG: false,
      // 支付方式
      paymentMethodValue: [
        { id: 0, value: '支付宝' },
        { id: 1, value: '微信' },
        { id: 2, value: '银行卡' }
      ],
      // 租户列表
      getPark: [],
      // 楼宇列表
      getBuilding: [],
      formModel: {
        selectedPark: null, // 初始化租户选择
        selectedBuilding: null, // 初始化楼宇选择
        paymentPeriod: [], // 初始化缴费周期
        paymentAmount: '', // 初始化支付金额
        paymentMethod: null // 初始化支付方式
      },
      searchForm: {
        enterpriseName: '', // 查询的企业名称
        paymentPeriod: [] // 查询的缴费时间段
      },
      viewForm: {}
    }
  },
  created() {
    this.getPropetyList()
    this.getParkList()
    this.getBuildingList()
  },
  methods: {
    flagOk() {
      this.flag = true
    },
    async getPropetyList() {
      const res = await getPropetyList({
        page: this.page,
        pageSize: this.pageSize,
        start: this.start,
        end: this.end,
        enterpriseName: this.enterpriseName
      })
      this.parklist = res.data.rows
      this.total = res.data.total
    },
    handleCurrentChange(val) {
      this.page = val
      this.getPropetyList()
    },
    async getParkList() {
      const res = await getParkList()
      this.getPark = res.data
    },
    async getBuildingList() {
      const res = await getBuildingList()
      this.getBuilding = res.data
    },
    submitForm() {
      console.log('Form Submitted:', this.formModel)
      // 这里可以添加表单提交逻辑
      this.flag = false
    },
    // 添加账单
    async addFn() {
      await addpropertyAPI({
        enterpriseId: this.formModel.selectedPark,
        buildingId: this.formModel.selectedBuilding,
        startTime: this.formModel.paymentPeriod[0].toISOString(),
        endTime: this.formModel.paymentPeriod[1].toISOString(),
        paymentAmount: parseFloat(this.formModel.paymentAmount),
        paymentMethod: parseInt(this.formModel.paymentMethod)
      })
      this.$message.success('账单添加成功')
      this.resetForm()
      this.getPropetyList()
      this.flag = false
    },
    resetForm() {
      this.formModel = {
        selectedPark: null,
        selectedBuilding: null,
        paymentPeriod: [],
        paymentAmount: '',
        paymentMethod: null
      }
    },
    async delFn(id) {
      await deletePropertyAPI(id)
      this.getPropetyList()
      this.$message.success('删除成功')
    },
    // 搜索
    async chaxun() {
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          enterpriseName: this.searchForm.enterpriseName,
          startTime: this.searchForm.paymentPeriod.length > 0 ? this.searchForm.paymentPeriod[0].toISOString() : '',
          endTime: this.searchForm.paymentPeriod.length > 0 ? this.searchForm.paymentPeriod[1].toISOString() : ''
        }

        const res = await getPropetyList(params)
        this.parklist = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.error('查询失败:', error)
        this.$message.error('查询过程中出现了错误，请稍后再试')
      }
    },
    // 查看
    async chakan(id) {
      // 调用后台接口获取指定id的账单详情
      const res = await lookAPI(id)
      // 将返回的数据映射到viewForm
      this.viewForm = {
        billNumber: res.data.billNumber,
        buildingName: res.data.buildingName,
        startTime: new Date(res.data.startTime).toLocaleString(), // 格式化日期时间
        endTime: new Date(res.data.endTime).toLocaleString(), // 格式化日期时间
        enterpriseName: res.data.enterpriseName,
        paymentAmount: res.data.paymentAmount,
        paymentMethodValue: this.paymentMethodValue.find(method => method.id === res.data.paymentMethod)?.value || '', // 根据id查找支付方式名称
        propertyFeePrice: res.data.propertyFeePrice
      }
      // 显示查看账单对话框
      this.FLAG = true
    }

  }
}
</script>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
  .search-btn{
    margin-left:20px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
